const API = 'http://39.104.24.231:8082/news'
const TAGS = [1, 2, 3, 4, 5]

Page({
  data: {
    tabs: TAGS.map(String),
    activeTab: 0,
    newsList: []
  },

  onLoad() {
    this.loadNews()
  },

  loadNews() {
    const tag = TAGS[this.data.activeTab]
    const url = `${API}/tag/${tag}`

    wx.request({
      url,
      success: res => {
        if (res.data.status === 200) {
          const newData = res.data.data.map(item => ({
            id: item.id,
            title: item.title,
            author: item.author ,
            date: item.date.split('T')[0],
            text: item.text,
            image: item.image,
            agreeNumber: item.agreeNumber
          }))

          this.setData({
            newsList: newData
          })
        } 
      },
      fail: () => {
        wx.showToast({ title: '加载失败', icon: 'none' })
      }
    })
  },

  handleTabTap(e) {
    const index = e.currentTarget.dataset.index
    this.setData({ 
      activeTab: index
    }, () => this.loadNews())
  },

  handleNewsTap(e) {
    const index = e.currentTarget.dataset.index
    const newsItem = this.data.newsList[index]
    wx.navigateTo({
      url: `/pages/detail/detail?data=${encodeURIComponent(JSON.stringify(newsItem))}`
    })
  }
})